#include <stdlib.h>
#include <stdio.h>
#include <conio.h>
#include <string.h>
#include <locale.h>


void main(int count, const char *values[])
{
	FILE *input_file;
	FILE *output_file;

	int reading = 1;
	int kolvo;
	int i;
	int PF = 38;
	int regim = 0;

	unsigned int nextsimbol;
	unsigned int simbol;

	setlocale(LC_ALL, "ru_ru");

	if (count == 4)
	{
		if (strcmp(values[1], "c") == 0)
			regim = 1;

		else if (strcmp(values[1], "d") == 0)
			regim = 2;

	}
	else
	{
		printf("fail arguments,,, ERROR\n");
		return;
	}

	input_file =  fopen(values[2], "rb");
	output_file = fopen(values[3], "wb");

	if (input_file == NULL || output_file == NULL )
	{
		printf(" Fail %s or %s file\n", "input_file","output_file");
		system("pause");
		return;
	}

	if (regim == 1){
		simbol = fgetc(input_file);	
		while(reading){

			kolvo = 1;
			if (simbol == -1)
				break;

			while (true){
				nextsimbol = fgetc(input_file);
				if (nextsimbol == simbol){
					kolvo ++;
					if (kolvo > 254)
						break;
				}
				else {
					if (nextsimbol == -1 || simbol == -1)
						reading = 0;
					break;
				}
			}		
			if (kolvo <= 3 && simbol != '&'){
				for(i = 0; i < kolvo; i ++){
					fputc(simbol, output_file);
				}
			}
			else{		
				fputc(PF,output_file);
				fputc(kolvo, output_file);
				fputc(simbol,output_file);
			}

			simbol = nextsimbol;
		}
	}

	if (regim == 2){
		while(1){
			simbol = fgetc(input_file);
			if (simbol == -1)
				break;
			if(simbol != '&')
				fputc(simbol, output_file);
			else{
				kolvo = fgetc(input_file);
				simbol = fgetc(input_file);
				for(i = 0; i < kolvo; i ++){
					fputc(simbol, output_file);
				}
			}
		}

	}

	printf("OK\n");
	system("pause");



	fclose(input_file);
	fclose(output_file);
}